In this exercise we will look at different adaptive Metropolis algorithms. The aim is to get an intuition for what their “adaptations” are doing, by examining their behaviour with our simple monod model. You are encouraged to play with each of the adaptation parameters of each algorithm and to check how it influences the resulting sample chain.

Define posterior distribution

You can use you own code from exercises 2 or the functions defined below. And of course you can also do the exercises with the growth model.

R

## load the monod model
source("../../models/models.r")

## read data
data.monod <- read.table("../../data/model_monod_stoch.csv", header=T)

## Logprior for model "monod": lognormal distribution
prior.monod.mean <- 0.5 * c(r_max=5, K=3, sigma=0.5)
prior.monod.sd   <- 0.5 * prior.monod.mean

logprior.monod <- function(par, mean, sd){
    sdlog <- sqrt(log(1+sd*sd/(mean*mean)))
    meanlog <- log(mean) - sdlog*sdlog/2
    return(sum(dlnorm(par, meanlog=meanlog, sdlog=sdlog, log=TRUE)))
}

## Log-likelihood for model "monod"
loglikelihood.monod <- function(y, C, par){

    ## deterministic part:
    y.det <- model.monod(par, C) # defined in `models.r`

    ## Calculate loglikelihood assuming independence:
    return( sum(dnorm(y, mean=y.det, sd=par['sigma'], log=TRUE )) )
}

## Log-posterior for model "monod"
logposterior.monod <- function(par) {
    lp <- logprior.monod(par, prior.monod.mean, prior.monod.sd)
    if(is.finite(lp)){
        return( lp + loglikelihood.monod(data.monod$r, data.monod$C, par) )
    } else {
        return(-Inf)
    }
}

Julia

using DataFrames
import CSV
using Distributions
using ComponentArrays

## load monod model
include("../../models/models.jl");

## read data
monod_data = CSV.read("../../data/model_monod_stoch.csv", DataFrame)

# set parameters
prior_monod_mean = ComponentVector(r_max = 2.5, K=1.4, sigma=0.25);
prior_monod_sd = 0.5 .* prior_monod_mean;

## Use a lognormal distribution for all model parameters
function logprior_monod(par, m, sd)
    μ = @. log(m/sqrt(1+sd^2/m^2))
    σ = @. sqrt(log(1+sd^2/m^2))
    return sum(logpdf.(LogNormal.(μ, σ), par)) # sum because we are in the log-space
end

## Log-likelihood for model "monod"
function loglikelihood_monod(par::ComponentVector, data::DataFrame)
    y_det = model_monod(data.C, par)
    return sum(logpdf.(Normal.(y_det, par.sigma), data.r))
end

## Log-posterior for model "monod"
function logposterior_monod(par::ComponentVector)
    lp = logprior_monod(par, prior_monod_mean, prior_monod_sd)
    if !isinf(lp)
        lp += loglikelihood_monod(par, monod_data)
    end
    lp
end

1. Adaptive Metropolis with delayed rejection ★

We try the adaptive Metropolis with delayed rejection as described by (Haario, Saksman and Tamminen (2001).

  • What could you use as initial values?

  • What is a meaningful initial covariance matrix for the jump distribution?

  • Plot the chains and see how quick the convergence is.

  • Look at 2d marginal plots. What happens in these marginal plots if you don’t cut off a burn-in or only use the beginning of the chain?

Hints

R

It is implemented in the function modMCMC of the package FME. Note, this function expects the negative log density”, which is sometimes called energy. See the modMCMC function documentation for details.

neg.log.post <- function(par) -logposterior.monod(par)

Now call the modMCMC function and investigate the effects of the updatecov parameter (try values of 10, 100 and 1000), which determines how often the covariance of the jump distribution is updated, and the ntrydr parameter (try values of 1, 3 and 10), which determines the number of permissible jump attempts before the step is rejected. In particular, examine the first part of the chain and see how the adaptation works.

AMDR <- modMCMC(
    f         = neg.log.post,
    p         = par.init,
    jump      = jump.cov,
    niter     = 10000,
    updatecov = 10,
    ntrydr    = 3
)

Julia

The package AdaptMCMC provides multiple MCMC algorithms including the adaptive Metropolis.

using ComponentArrays
using AdaptiveMCMC
using MCMCChains
using Plots
using StatsPlots

θinit = ComponentVector(r_max=..., K=..., sigma=...)

res = adaptive_rwm(θinit, logposterior_monod,
                   10_000;
                   algorithm = :am,
                   b=1,   # length of burn-in. Set to 1 for no burn-in.
                   );

# convert to MCMCChains for summary and plotting
chn = Chains(res.X', labels(θinit))

plot(chn)
corner(chn)

Solution

R

library(FME)
## Loading required package: rootSolve
library(IDPmisc)
neg.log.post <- function(par) -logposterior.monod(par)

The mean of the prior seems to be a reasonable point to start the sampler. Alternatively, we could try to find the point of the maximum posterior density with an optimizer. For the covariance matrix of the jump distribution we use the standard deviation of the prior and assume independence.

par.init <- prior.monod.mean
jump.cov <- diag(prior.monod.sd/2)

par.init <- prior.monod.mean
jump.cov <- diag(prior.monod.sd/2)

AMDR <- FME::modMCMC(f         = neg.log.post,
                     p         = par.init,
                     jump      = jump.cov,
                     niter     = 10000,
                     updatecov = 10,
                     ntrydr    = 3
                     )
## number of accepted runs: 8146 out of 10000 (81.46%)
## plot chains
plot(AMDR)

## 2d marginals
pairs(AMDR$pars)

IDPmisc::ipairs(AMDR$pars)

Julia

using ComponentArrays
using AdaptiveMCMC
using MCMCChains
using Plots
using StatsPlots

θinit = ComponentVector(r_max = 2.5, K=1.4, sigma=0.25) # use prior mean
## ComponentVector{Float64}(r_max = 2.5, K = 1.4, sigma = 0.25)
res = adaptive_rwm(θinit, logposterior_monod,
                   10_000;
                   algorithm = :am,
                   b=1,   # length of burn-in. Set to 1 for no burn-in.
                   );
# convert to MCMCChains for summary and plotting
chn = Chains(res.X', labels(θinit))
## Chains MCMC chain (10000×3×1 reshape(adjoint(::Matrix{Float64}), 10000, 3, 1) with eltype Float64):
## 
## Iterations        = 1:1:10000
## Number of chains  = 1
## Samples per chain = 10000
## parameters        = r_max, K, sigma
## 
## Summary Statistics
##   parameters      mean       std      mcse   ess_bulk    ess_tail      rhat    ⋯
##       Symbol   Float64   Float64   Float64    Float64     Float64   Float64    ⋯
## 
##        r_max    4.4072    0.3290    0.0129   666.6024    198.4136    1.0068    ⋯
##            K    1.6587    0.4551    0.0195   714.5639    653.2035    1.0043    ⋯
##        sigma    0.4710    0.0716    0.0024   906.3260   1290.8312    1.0028    ⋯
##                                                                 1 column omitted
## 
## Quantiles
##   parameters      2.5%     25.0%     50.0%     75.0%     97.5%
##       Symbol   Float64   Float64   Float64   Float64   Float64
## 
##        r_max    3.8554    4.1898    4.3739    4.6071    5.1302
##            K    0.9455    1.3292    1.5916    1.9236    2.7138
##        sigma    0.3577    0.4197    0.4621    0.5121    0.6337
plot(chn)

corner(chn)

2. Robust adaptive Metropolis ★

The robust adaptive Metropolis algorithm proposed by Vihola (2012) is often a good choice. It adapts the scale and rotation of the covariance matrix until it reaches a predefined acceptance rate.

  • Did the algorithm reach the desired acceptance rate?

  • How is the covariance matrix after the adaptation different from the initial covariance that you provided?

Hints

R

The package adaptMCMC provides the function MCMC. If the parameter adapt is set to TRUE it implements the adaptation propsoed by Vihola. Again examine the effect of the adaptation settings on the chains, in particular examining the first part of the chain to see how the adaptation works. Here the adaptation is determined by parameter acc.rate. Try values between 0.1 and 1.

How is the influence on the burn-in? What happens, if you use a very bad initial value?

RAM <- MCMC(
    p        = logposterior.monod,
    n        = 10000,
    init     = par.start,
    scale    = jump.cov,
    adapt    = TRUE,
    acc.rate = 0.5
)

str(RAM)

Julia

The package AdaptMCMC provides multiple MCMC algorithms including the robust adaptive Metropolis.

using ComponentArrays
using AdaptiveMCMC
using MCMCChains
using Plots
using StatsPlots

θinit = ComponentVector(r_max=..., K=..., sigma=...)

res = adaptive_rwm(θinit, logposterior_monod,
                   10_000;
                   algorithm = :ram,
                   b=1,   # length of burn-in. Set to 1 for no burn-in.
                   );

# convert to MCMCChains for summary and plotting
chn = Chains(res.X', labels(θinit))

plot(chn)
corner(chn)

Solution

R

library(adaptMCMC)
library(IDPmisc)

The mean of the prior seems to be a reasonable point to start the sampler. Alternatively, we could try to find the point of the maximum posterior density with an optimizer. For the covariance matrix of the jump distribution we use the standard deviation of the prior and assume independence.

par.init <- prior.monod.mean
jump.cov <- diag(prior.monod.sd/2)

RAM <- adaptMCMC::MCMC(p        = logposterior.monod,
                       n        = 10000,
                       init     = par.init,
                       scale    = jump.cov,
                       adapt    = TRUE,
                       acc.rate = 0.5,
                       showProgressBar = FALSE)
##   generate 10000 samples

The acceptance rate is matched closely:

RAM$acceptance.rate
## [1] 0.498

The adapted covariance matrix has a lot of correlation between \(r_{max}\) and \(K\):

RAM$cov.jump
##              [,1]         [,2]         [,3]
## [1,]  0.037693378  0.041642344 -0.001012118
## [2,]  0.041642344  0.062843240 -0.001158813
## [3,] -0.001012118 -0.001158813  0.001628899
cov2cor(RAM$cov.jump) # rescale as correlation matrix
##            [,1]       [,2]       [,3]
## [1,]  1.0000000  0.8556051 -0.1291670
## [2,]  0.8556051  1.0000000 -0.1145347
## [3,] -0.1291670 -0.1145347  1.0000000
## plot chains
samp.coda <- convert.to.coda(RAM)
plot(samp.coda)

## 2d marginals
IDPmisc::ipairs(RAM$samples) # prettier versions of pairs()

Julia

using ComponentArrays
using AdaptiveMCMC
using MCMCChains
using Plots
using StatsPlots

θinit = ComponentVector(r_max = 2.5, K=1.4, sigma=0.25) # use prior mean
## ComponentVector{Float64}(r_max = 2.5, K = 1.4, sigma = 0.25)
res = adaptive_rwm(θinit, logposterior_monod,
                   10_000;
                   algorithm = :ram,
                   b=1,   # length of burn-in. Set to 1 for no burn-in.
                   );
# convert to MCMCChains for summary and plotting
chn = Chains(res.X', labels(θinit))
## Chains MCMC chain (10000×3×1 reshape(adjoint(::Matrix{Float64}), 10000, 3, 1) with eltype Float64):
## 
## Iterations        = 1:1:10000
## Number of chains  = 1
## Samples per chain = 10000
## parameters        = r_max, K, sigma
## 
## Summary Statistics
##   parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e ⋯
##       Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯
## 
##        r_max    4.3705    0.3282    0.0127   656.9159   722.5235    1.0015     ⋯
##            K    1.6084    0.4369    0.0188   573.5799   583.3838    1.0036     ⋯
##        sigma    0.4763    0.0925    0.0040   655.8783   440.8117    0.9999     ⋯
##                                                                 1 column omitted
## 
## Quantiles
##   parameters      2.5%     25.0%     50.0%     75.0%     97.5%
##       Symbol   Float64   Float64   Float64   Float64   Float64
## 
##        r_max    3.7739    4.1575    4.3640    4.5799    5.0400
##            K    0.8645    1.3017    1.5529    1.8819    2.6004
##        sigma    0.3586    0.4211    0.4667    0.5153    0.6547
plot(chn)

corner(chn)

3. Population based sampler ★

Population based samplers do not have an explicit jump distribution. Instead, they run multiple chains (often called particles or walkers in this context) in parallel and the proposals are generated based on the position of the other particles.

A popular algorithm of this class is the Affine-Invariant MCMC population sampler proposed by Goodman and Weare (2010). The algorithm is often called EMCEE based on the python package with the same name.

Hints

R

Population based samplers are implemented in the package mcmcensemble as MCMCEnsemble. It has two methods: stretch move (method = "stretch") and differential evolution (method = "differential.evolution").

EMCEE <- MCMCEnsemble(
    f           = logposterior.monod,
    lower.inits = par.start.lower,
    upper.inits = par.start.upper,
    max.iter    = 10000,
    n.walkers   = n.walkers,
    method      = "stretch",
    coda        = FALSE
)
  • How do you choose par.start.lower and par.start.upper? Better wide or narrow?

  • What is the influence of the number of walkers?

  • Which method works better in this case?

Julia

We use the package KissMCMC which provides a function emcee:

using ComponentArrays
using KissMCMC: emcee
using Plots
using StatsPlots

# number of walkers (parallel chains)
n_walkers = 10

## We need a vector of inital values, one for each walkers.
## Make sure that they do not start from the same point.
θinits = [θinit .* rand(3) for _ in 1:n_walkers]

# Run sampler
samples, acceptance_rate, lp = emcee(logposterior_monod,
                                     θinits;
                                     niter = 10_000, # total number of density evaluations
                                     nburnin = 0);

# This looks a bit ugly. It just converts the result into
# a `MCMCChains.Chains` object for plotting.
X = permutedims(
    cat((hcat(samples[i]...) for i in 1:n_walkers)..., dims=3),
    [2, 1, 3]);
chn = Chains(X, labels(θinit))

# plotting
plot(chn)
corner(chn)
  • How do you define the initial values? Very similar or very different?

  • What is the influence of the number of walkers?

Solution

R

library(mcmcensemble)

For each walker (chain) an initial starting point must be defined. In general, it is better to choose it in a region with high density. We could use an optimizer to fine the mode, but here we just use a rather wide coverage.

n.walkers <- 20
par.inits <- data.frame(r.max = runif(n.walkers, 1, 10),
                        K     = runif(n.walkers, 0, 5),
                        sigma = runif(n.walkers, 0.05, 2))
EMCEE <- MCMCEnsemble(
    f           = logposterior.monod,
    inits       = par.inits,
    max.iter    = 10000,
    n.walkers   = n.walkers,
    method      = "stretch",
    coda        = TRUE
)
## Using stretch move with 20 walkers.
plot(EMCEE$samples)

Note, the more walkers (chains) we have, the shorter the chains. This means we have to “pay” the burn in for every single chain. Therefore, going too extreme with the number of chains is not beneficial.

n.walkers <- 1000
par.inits <- data.frame(r.max = runif(n.walkers, 1, 10),
                        K     = runif(n.walkers, 0, 5),
                        sigma = runif(n.walkers, 0.05, 2))

EMCEE <- MCMCEnsemble(
    f           = logposterior.monod,
    inits       = par.inits,
    max.iter    = 10000,
    n.walkers   = n.walkers,
    method      = "stretch",
    coda        = TRUE
)
## Using stretch move with 1000 walkers.
plot(EMCEE$samples)

Julia

using ComponentArrays
using KissMCMC: emcee
using Plots
using StatsPlots

# number of walkers (parallel chains)
n_walkers = 10;

## We need a vector of inital values, one for each walkers.
θinit = ComponentVector(r_max = 2.5, K=1.4, sigma=0.25); # prior mean
## ComponentVector{Float64}(r_max = 2.5, K = 1.4, sigma = 0.25)
## We add some randomnesses to make sure that they do not start
## from the same point.
θinits = [θinit .* rand(Normal(0, 0.1), 3) for _ in 1:n_walkers];

# Run sampler
samples, acceptance_rate, lp = emcee(logposterior_monod,
                                     θinits;
                                     niter = 10_000, # total number of density evaluations
                                     nburnin = 0);

# Converting into `MCMCChains.Chains` object for plotting.
X = permutedims(
    cat((hcat(samples[i]...) for i in 1:n_walkers)..., dims=3),
    [2, 1, 3]);
chn = Chains(X, labels(θinit))
## Chains MCMC chain (1000×3×10 Array{Float64, 3}):
## 
## Iterations        = 1:1:1000
## Number of chains  = 10
## Samples per chain = 1000
## parameters        = r_max, K, sigma
## 
## Summary Statistics
##   parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e ⋯
##       Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯
## 
##        r_max    4.3476    0.9009    0.0563   233.8062   155.2063    1.0524     ⋯
##            K    1.6977    0.9597    0.0587   226.6224   181.3022    1.0546     ⋯
##        sigma    0.4371    0.1208    0.0114   137.6256   155.4724    1.0457     ⋯
##                                                                 1 column omitted
## 
## Quantiles
##   parameters      2.5%     25.0%     50.0%     75.0%     97.5%
##       Symbol   Float64   Float64   Float64   Float64   Float64
## 
##        r_max    1.5309    4.1766    4.4074    4.6319    5.4304
##            K    0.1941    1.3162    1.6077    1.9293    3.2566
##        sigma    0.0637    0.4037    0.4526    0.5028    0.6130

Note, that our chains are only of length 1000. So we have a lot of computation used for the burn-in phase.

# plotting
plot(chn)

corner(chn)

# removing burn-in:
corner(chn[250:end,:,:])

4. Posterior Predictions ★

In many cases we want to make predictions for new model inputs. Let’s say we have observed the data \((y, x)\) and used it to infer the posterior \(p(\theta | y, x)\). We would now like to make predictions given a new input \(x^*\) using the learned posterior distribution:

\[ p(Y^* | x^*, y, x,) = \int p(Y^* | x^*, \theta) \, p(\theta | y, x) \text{d}\theta \]

  • For the monod model, what is \(p(Y^* | x^*, \theta)\)?

  • Produce predictions for the monod model for \(C = \{10, 12, 14, 16\}\) using a posterior sample from a exercises. We only need samples form the predictive distribution. How can you do this without solving the integral analytically?

  • Plot the result with 90% prediction interval.

  • How much do you trust that the interval is correct? What assumptions did you make?

Solution

  • The expression \(p(Y^* | x^*, \theta)\) is our probabilistic model, so the distribution of \(Y^*\) given some inputs and parameters (i.e. the likelihood function).

  • Typically we do not have the posterior distribution \(p(\theta | y, x)\) in analytical form but a sample from it. Hence we cannot compute the integral over all \(\theta\) (besides that this would be difficult anyway). Instead, we use an approach to obtain samples from \(Y^*\):

    1. Take a sample \(\theta'\) from \(p(\theta | y, x)\).
    2. Take a sample from \(p(Y^* | x^*, \theta')\).

    Both steps are computationally cheap. For 1) we already have samples from the parameter inference, and 2) is simply a forward simulation of the model as we did in exercises 1. Hence, producing posterior predictions is much cheaper than inference.

    (Technically we sample from the joint distribution \(p(Y^*, \theta| x^*, y, x)\)). The marginalization over \(\theta\) is done by simply ignoring the sampled \(\theta\)s and looking only at \(Y^*\).)

  • It is important to keep in mind that the resulting prediction intervals are only correct as long the underlying model is correct! For example, it seems rather risky to extrapolate with the monod model to large concentrations outside of the calibration data range.

R

We take the function for forward simulations from exercises 1:

simulate.monod.stoch <- function(par, C){
    ## run model
    r.det <- model.monod(par, C)

    ## generate noise
    z <- rnorm(length(C), 0, par["sigma"])

    return(r.det + z)
}
m <- 1000 # number of samples

Cstar <- c(10, 12, 14, 16)               # new inputs

## posterior samples, removing burn-in
post.samples <- RAM$samples[1000:10000,]

Ystar <- matrix(NA, ncol=length(Cstar), nrow=m)
colnames(Ystar) <- paste0("C_", Cstar)
for(k in 1:m){
    ## 1) take a sample from posterior
    i <- sample(ncol(post.samples), 1)
    theta <- post.samples[i,]

    ## 2) forward simulation from model
    Ystar[k,] <- simulate.monod.stoch(theta, Cstar)
}

We can also plots the predictions with uncertainty bands:

Ystar.quants <- apply(Ystar, MARGIN=2, FUN=quantile, probs=c(0.05, 0.5, 0.95))

## plot result
plot(Cstar, Ystar.quants[2,], ylab="r", ylim=c(0, 5))
polygon(c(Cstar,rev(Cstar)), c(Ystar.quants[1,],rev(Ystar.quants[3,])), col = "grey85")
lines(Cstar, Ystar.quants[2,], col=2, lwd=2, type="b")

Julia

We take the function for forward simulations from exercises 1:

# function to simulate stochastic realisations
function simulate_monod_stoch(C, par)
    Ydet = model_monod(C, par)
    z = rand(Normal(0, par.sigma), length(Ydet)) # adding noise
    Ydet .+ z
end
## simulate_monod_stoch (generic function with 1 method)
m = 1000
## 1000
Cstar = [10,12,14,16]
## 4-element Vector{Int64}:
##  10
##  12
##  14
##  16
Ystar = Matrix{Float64}(undef, m, length(Cstar));
θ = copy(θinit);
for k in 1:m
    i = rand(1000:10000)
    θ .= res.X[:,i]
    Ystar[k,:] = simulate_monod_stoch(Cstar, θ)
end
# compute quantile
low_quantile = [quantile(Ystar[:,i], 0.05) for i in 1:length(Cstar)];
med_quantile = [quantile(Ystar[:,i], 0.5) for i in 1:length(Cstar)];
upper_quantile = [quantile(Ystar[:,i], 0.95) for i in 1:length(Cstar)];
plot(Cstar, upper_quantile,
     fillrange = low_quantile,
     labels = false,
     xlabel = "C",
     ylabel = "r",
     ylim=(0,5));
plot!(Cstar, med_quantile, marker=:circle,
      labels = false)

5. Gradient based samplers ♛

If we are able to compute the gradient of the log density, \(\nabla \log p\), we can use much more efficient sampling methods. For small numbers of parameters this may not be relevant, for larger problems (more than 20 dimensions) the differences can be huge.

Julia is particularly well suited for these applications, because many libraries for Automatic Differentiation (AD) are available - methods that compute the gradient of (almost) any Julia function by analyzing the code.

Because there is no equally powerful AD available in R, we can do this exercise only with Julia.

Parameter transformation

Most gradient based samplers assume that all parameters are in \(\mathbb{R}\). If we have a parameter that is only defined on an interval, such as a standard deviation that is never negative, we need to transform the model parameter before sampling. For this we need three ingredients:

  • a function that maps every vector in \(\mathbb{R}^n\) to our “normal” model parameter space,

  • the inverse of this function,

  • the determinant of the Jacobian of this function.

The package TransformVariables helps us with these transformations. We need a function that takes a vector in \(\mathbb{R}^n\) to evaluate the posterior.

using TransformVariables

# defines the 'legal' parameter space, all parameter cannot be negative
# due to the lognormal prior
trans = as((r_max = asℝ₊, K = asℝ₊, sigma = asℝ₊))

We can now sample in \(\mathbb{R}^n\) and later transform the samples to the model parameter space with:

TransformVariables.transform(trans, [-1,-1,-1]) # -> (r_max=0.367, K=0.367, sigma=0.367)

Automatic Differentation

The last ingredient we need is a function that computes the gradient of logposterior_monod_Rn. To do so we need to differentiate through our model, the likelihood, the prior, the parameter transformation, and the determinant of the Jaccobian. Needles to say, even for our very simple model this would be very tedious to do manually!

Instead we use Automatic Differentiation (AD). Julia has multiple packages for AD that make different trade-offs. We use ForwardDiff that is well suited for smaller dimensions.

AD requires all your model code to be implemented in pure Julia! Otherwise there are few restrictions. For example, you can compute the gradient of the growth model even though it uses an advanced adaptive ODE solver internally.

using TransformedLogDensities: TransformedLogDensity
using LogDensityProblemsAD: ADgradient

# Define an object that is compatible with the LogDensityProblems.jl interface. 
# It requires a parameter transformation and a function to compute the 
# log probability density
# This inyterface enables compability with different samplers.
lp = TransformedLogDensity(trans, θ -> logposterior_monod(ComponentVector(θ)))

lp = ADgradient(:ForwardDiff, lp) # define the AD framework to use

Hamiltonian Monte Carlo

Hamiltonian Monte Carlo (HMC) is one of the most powerful methods to sample in high dimensions. The “No-U-Turn Sampler” (NUTS) is a popular version. For example, it is used in STAN.

The package DynamicHMC.jl provides a robust implementation.

HMC samplers need many density- and gradient-evaluations to produce a single proposal. However, the acceptance rate of an HMC sampler should be close to one. We can use the wrapper function stanHMC like this:

import Random
using DynamicHMC: mcmc_with_warmup, ProgressMeterReport, Diagnostics.summarize_tree_statistics

# run for 100 samples
par_init = [-1.0, -1.0, -1.0];   # in ℝⁿ

results = mcmc_with_warmup(Random.GLOBAL_RNG, lp, 100;
                           initialization = (q = par_init, ),
                           reporter = ProgressMeterReport());

The samples we get are in \(\mathbb{R}^n\). Before we have a look, let’s transform them to the “normal” parameter space:

# back-transform samples
_samples = [TransformVariables.transform(trans, s)
            for s in eachcol(results.posterior_matrix)];

samples = vcat((hcat(i...) for i in _samples)...);
chn = MCMCChains.Chains(samples,  [:r_max, :K, :sigma])

plot(chn)

BarkerMCMC

Livingstone and Zanella (2021) proposed a comparably simple MCMC algorithm that uses the gradient to adapt the jump distribution. It is a promising alternative to HMC in cases where the number of parameters is not very high, or if the gradient is expected to be noisy (which is often the case if a model uses adaptive ODE solvers).

BarkerMCMC.jl implements it including an adaptation that aims at a given acceptance rate.

using BarkerMCMC: barker_mcmc

par_init = [-1.0, -1.0, -1.0]   # note, this is in ℝⁿ

# see `?barker_mcmc` for all options
res = barker_mcmc(lp,
                  par_init;
                  n_iter = 1000,
                  target_acceptance_rate=0.4);

res.samples                     # this are the samples in ℝⁿ !
res.log_p

The samples we get are in \(\mathbb{R}^n\). Before we have a look, let’s transform them to the “normal” parameter space:

using MCMCChains
using StatsPlots

# Transform the samples to the "normal" space and convert to `Chains`
_samples = [TransformVariables.transform(trans, s)
            for s in eachrow(res.samples)];
samples = vcat((hcat(i...) for i in _samples)...);
chn = Chains(samples,  [:r_max, :K, :sigma])

plot(chn)
corner(chn)

Solution

Julia

First we make sure, that we can sample in an unlimited space by using a appropriate transformations:

using TransformVariables
using TransformedLogDensities: TransformedLogDensity
using LogDensityProblemsAD: ADgradient

# defines the 'legal' parameter space, all parameter cannot be negative
# due to the lognormal prior
trans = as((r_max = asℝ₊, K = asℝ₊, sigma = asℝ₊))
## [1:3] NamedTuple of transformations
##   [1:1] :r_max → asℝ₊
##   [2:2] :K → asℝ₊
##   [3:3] :sigma → asℝ₊

# define an object that is compatible with the LogDensityProblems.jl interface.
# This enables compability with idfferent samplers.
lp = TransformedLogDensity(trans, θ -> logposterior_monod(ComponentVector(θ)))
## TransformedLogDensity of dimension 3

We compute the gradient of the logposterior with automatic differentiation (AD). In Julia we can choose AD different back-ends. ForwardDiff.jl is a good option if we do not have many parameters.

lp = ADgradient(:ForwardDiff, lp)
## ForwardDiff AD wrapper for TransformedLogDensity of dimension 3, w/ chunk size 3

HMC

We use a “No-U-turn sampler” HMC sampler, similar to the one implemented in STAN. Note, that for HMC we typically need a much lower number of samples.

import Random
using DynamicHMC: mcmc_with_warmup, ProgressMeterReport, Diagnostics.summarize_tree_statistics

# run for 100 samples
par_init = [-1.0, -1.0, -1.0];   # in ℝⁿ
## 3-element Vector{Float64}:
##  -1.0
##  -1.0
##  -1.0

results = mcmc_with_warmup(Random.GLOBAL_RNG, lp, 100;
                           initialization = (q = par_init, ),
                           reporter = ProgressMeterReport());

# some convergence statistics
summarize_tree_statistics(results.tree_statistics)
## Hamiltonian Monte Carlo sample of length 100
##   acceptance rate mean: 0.94, 5/25/50/75/95%: 0.73 0.92 0.97 0.99 1.0
##   termination: divergence => 0%, max_depth => 0%, turning => 100%
##   depth: 0 => 0%, 1 => 0%, 2 => 22%, 3 => 53%, 4 => 25%

results.posterior_matrix                     # this are the samples in ℝⁿ !
## 3×100 Matrix{Float64}:
##   1.47899    1.55212    1.4968    …   1.38672    1.49463    1.39449
##   0.291095   0.548337   0.709235      0.255031   0.510595   0.127088
##  -0.858361  -0.741744  -0.828165     -0.696111  -0.768266  -0.74918

We need to back-transform the samples to the “normal” parameter space. For plotting we convert to MCMCChains.Chains:

# back-transform samples
_samples = [TransformVariables.transform(trans, s)
            for s in eachcol(results.posterior_matrix)];

samples = vcat((hcat(i...) for i in _samples)...);
chn = MCMCChains.Chains(samples,  [:r_max, :K, :sigma])
## Chains MCMC chain (100×3×1 Array{Float64, 3}):
## 
## Iterations        = 1:1:100
## Number of chains  = 1
## Samples per chain = 100
## parameters        = r_max, K, sigma
## 
## Summary Statistics
##   parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e ⋯
##       Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯
## 
##        r_max    4.4321    0.2614    0.0487    18.6900    44.5810    1.0702     ⋯
##            K    1.6570    0.3721    0.0626    33.7416    45.7499    1.0417     ⋯
##        sigma    0.4497    0.0745    0.0083    76.9832    71.2875    0.9919     ⋯
##                                                                 1 column omitted
## 
## Quantiles
##   parameters      2.5%     25.0%     50.0%     75.0%     97.5%
##       Symbol   Float64   Float64   Float64   Float64   Float64
## 
##        r_max    3.9964    4.2536    4.3989    4.5804    5.0239
##            K    1.1392    1.3826    1.5872    1.8272    2.4940
##        sigma    0.3320    0.4045    0.4378    0.4897    0.6488

plot(chn)

corner(chn[25:end,:,:])

BarkerMCMC

The same steps are taken for the BarkerMCMC:

using BarkerMCMC: barker_mcmc

par_init = [-1.0, -1.0, -1.0];   # note, this is in ℝⁿ
## 3-element Vector{Float64}:
##  -1.0
##  -1.0
##  -1.0

# see `?barker_mcmc` for all options
res = barker_mcmc(lp,
                  par_init;
                  n_iter = 1000,
                  target_acceptance_rate=0.4);
# Transform the samples to the "normal" space and convert to `Chains`
_samples = [TransformVariables.transform(trans, s)
            for s in eachrow(res.samples)];
samples = vcat((hcat(i...) for i in _samples)...);
chn = Chains(samples,  [:r_max, :K, :sigma])
## Chains MCMC chain (1000×3×1 Array{Float64, 3}):
## 
## Iterations        = 1:1:1000
## Number of chains  = 1
## Samples per chain = 1000
## parameters        = r_max, K, sigma
## 
## Summary Statistics
##   parameters      mean       std      mcse   ess_bulk   ess_tail      rhat   e ⋯
##       Symbol   Float64   Float64   Float64    Float64    Float64   Float64     ⋯
## 
##        r_max    4.1856    0.6964    0.2227    18.1529    11.9370    1.0590     ⋯
##            K    1.4511    0.6015    0.1402    30.3948    12.2910    1.0307     ⋯
##        sigma    0.5429    0.2984    0.0874     7.2154    13.9628    1.1514     ⋯
##                                                                 1 column omitted
## 
## Quantiles
##   parameters      2.5%     25.0%     50.0%     75.0%     97.5%
##       Symbol   Float64   Float64   Float64   Float64   Float64
## 
##        r_max    2.7239    4.0231    4.2921    4.5389    5.1045
##            K    0.0779    1.1706    1.4679    1.8526    2.5979
##        sigma    0.3690    0.4319    0.4912    0.5507    0.9474

plot(chn)

corner(chn[250:end,:,:])